package cc.owoo.godpen.analysis.css;

import cc.owoo.godpen.analysis.StringAnalysis;

/**
 * 样式解析工具
 * Created by nimensei
 * 2022-05-30 下午 10:14
 **/
public class StyleStringAnalysis extends StringAnalysis {
    /**
     * 创建一个解析器
     *
     * @param chars 需要解析的字符串
     */
    public StyleStringAnalysis(char[] chars) {
        super(chars);
    }

    /**
     * 解析并返回下一个选择器组
     *
     * @param end 结束符
     * @return 选择器
     */
    public SelectorGroup nextSelectorGroup(char end) {
        return new SelectorAnalysis(this).analysis(end);
    }

    /**
     * 解析css属性
     *
     * @param end 结束符
     * @return 属性对象
     */
    public Property nextProperty(char end) {
        Property property = new Property();
        int before = -1;
        int after = -1;
        String name = null;
        while (hashNext()) {
            char c = next();
            if (c == ';' || c == end) {
                if (before != -1 && name != null && name.length() > 0) {
                    String value = substring(before, after == -1 ? getIndex() : after);
                    property.add(name, value);
                    name = null;
                }
                before = after = -1;
                if (c == end)
                    break;
                continue;
            }
            if (c == ':' && name == null) {
                if (before == -1) {
                    name = "";
                    continue;
                }
                name = substring(before, after == -1 ? getIndex() : after);
                before = after = -1;
                continue;
            }
            if (c <= 32) {
                if (after == -1 && before != -1)
                    after = getIndex();
            } else {
                if (before == -1)
                    before = getIndex();
                after = -1;
            }
        }
        return property;
    }

    /**
     * 跳过括号
     *
     * @param count 当前左括号数量
     */
    public void skipBracket(int count) {
        while (hashNext()) {
            char c = next();
            if (c == '{')
                ++count;
            else if (c == '}' && --count == 0)
                break;
        }
    }
}
